# -*- coding:utf-8 -*-
# File Name:tree_builder.py
# Author:jing
# Date:2018/12/21
from abc import ABC, abstractmethod
from importlib import import_module
from tkinter import Frame, Event, END
from tkinter.ttk import Treeview

import os

from werkzeug.utils import find_modules

from data import Desc

__author__ = 'jing'


class TreeBuilder(Frame, ABC):

    def get_tree_view(self, **kwargs):
        tree = Treeview(self, **kwargs)
        self._init_tree(tree, '', 'data')
        tree.bind('<Double-1>', self.node_clicked)
        return tree

    def _init_tree(self, tree: Treeview, parent_node, module):
        for m in find_modules(module, include_packages=True):
            item_module = import_module(m)
            path = getattr(item_module, '__path__', None)
            if not path:
                tree.insert(parent_node, END, text=m.split('.')[-1].replace('_', ' '), values=[m])
            else:
                node = tree.insert(parent_node, END, text=m.split('.')[-1]).replace('_', ' ')
                self._init_tree(tree, node, m)

    def node_clicked(self, node: Event):
        tree = node.widget
        values = tree.item(tree.focus())['values']
        if values:
            self.refresh_content(*values)

    @abstractmethod
    def refresh_content(self, *values):
        raise NotImplementedError
